<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="110px"
    >
      <el-form-item label="工单号" prop="workTaskNumber">
        <el-input
          v-model="queryParams.workTaskNumber"
          placeholder="请输入工单号/任务单号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="产品编号" prop="productNumber">
        <el-input
          v-model="queryParams.productNumber"
          placeholder="请输入产品编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="部件编号" prop="partNumber">
        <el-input
          v-model="queryParams.partNumber"
          placeholder="请输入部件编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="部件名称" prop="partName">
        <el-input
          v-model="queryParams.partName"
          placeholder="请输入部件名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="图纸图号" prop="drawingNumber">
        <el-input
          v-model="queryParams.drawingNumber"
          placeholder="请输入图纸图号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item label="生产班组" prop="productionTeam">
        <el-input
          v-model="queryParams.productionTeam"
          placeholder="请输入生产班组"
          clearable
          @keyup.enter="handleQuery"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery" type="primary">搜索</el-button>
        <el-button @click="resetQuery"> 重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <div style="width: 100%; height: 50px; display: flex; justify-content: space-between">
      <div>
        <el-button
          type="primary"
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['produce:course-electric-box:export']"
        >
          数据导出
        </el-button>
        <el-button
          type="primary"
          @click="changeOperate"
          :loading="loading"
          v-hasPermi="['produce:course-electric-box:operate']"
        >
          {{ isEdit ? '提交' : '指派' }}
        </el-button>
      </div>
      <el-button type="primary" @click="openTableTitleSet"> 表头设置 </el-button>
    </div>
    <el-table
      ref="multipleTableRef"
      border
      row-key="id"
      :height="tableHeight"
      :tree-props="{ children: 'children' }"
      default-expand-all
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        align="center"
        :selectable="isSelected"
        :reserve-selection="true"
        type="selection"
        fixed="left"
      />
      <el-table-column label="序号" align="center" prop="parentIndex" type="" fixed="left" />
      <el-table-column
        v-if="tableTitleList.length"
        :min-width="tableTitleList[1].width"
        :header-align="tableTitleList[1].headerAlign"
        :align="tableTitleList[1].align"
        :label="tableTitleList[1].label"
        :prop="tableTitleList[1].field"
      >
        <template #default="scope">
          <dict-tag
            v-if="tableTitleList[1].dictType"
            :type="tableTitleList[1].dictType"
            :value="scope.row[tableTitleList[1].field]"
          />
          <span v-else>{{ scope.row[tableTitleList[1].field] }}</span>
        </template>
      </el-table-column>
      <template v-for="(item, index) in tableTitleList">
        <el-table-column
          v-if="item.isTable && ![0, 1].includes(index)"
          :key="index"
          :type="item.type"
          :min-width="item.width"
          :header-align="item.headerAlign"
          :align="item.align"
          :label="item.label"
          :prop="item.field"
        >
          <template #default="scope">
            <template v-if="item.field === 'operator'">
              <!-- 计件指派作业者 -->
              <el-input
              v-if="scope.row.parent === undefined"
                class="fontHide"
                readonly
                v-model="scope.row.operator"
                :disabled="!isEdit"
               @click="openOperator(scope.row.operatorSimpleNumberArr, scope.row.parentIndex)"
              />
              <!-- 进度指派作业者 -->
              <!-- <el-input
                v-else-if="scope.row.parent !== undefined"
                class="fontHide"
                readonly
                v-model="scope.row.operator"
                :disabled="!isEdit"
                @click="
                  openOperator(scope.row.operatorSimpleNumberArr, scope.row.parent, scope.row.index)
                "
              /> -->
              <span v-else>{{ scope.row[item.field] }}</span>
            </template>
            <!-- 修改设备编码 -->
            <template v-else-if="item.field === 'deviceCode'">
              <span v-if="scope.row.dictReportWay === 10 || scope.row.parent !== undefined">{{
                scope.row[item.field]
              }}</span>
              <el-select
                v-else
                v-model="scope.row.deviceCode"
                filterable
                remote
                value-key="deviceCode"
                :remote-method="getSelectDeviceList"
                :loading="deviceLoading"
                @change="changeDevice(scope.row)"
                :disabled="!isEdit"
              >
                <el-option
                  v-for="item in deviceList"
                  :key="item['deviceCode']"
                  :label="item['deviceCode']"
                  :value="item['deviceCode']"
                />
              </el-select>
            </template>
            <!-- 细部工序显示百分比 -->
            <template v-else-if="['planQuantity', 'reportQuantity', 'completeQuantity', 'differenceQuantity'].includes(item.field)">
              <div>
                {{ scope.row.parent !== undefined ? scope.row[item.field] * + '%' : scope.row[item.field] }}
              </div>
            </template>
            <template v-else>
              <dict-tag v-if="item.dictType" :type="item.dictType" :value="scope.row[item.field]" />
              <template v-else>
                <el-button
                v-if="item.label == '图纸图号'"
                type="primary"
                link
                @click="jumpPdfFile(scope.row[item.field])"
                >{{ scope.row[item.field] }}</el-button
              >

              <span v-else>{{ scope.row[item.field] }}</span>
              </template>
            </template>
          </template>
        </el-table-column>
      </template>
      <el-table-column label="操作" header-align="left" align="left" width="80" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            v-if="scope.row.parentIndex"
            @click="openForm(scope.row.id)"
            v-hasPermi="['produce:course-electric-box:view']"
          >
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 导出 -->
  <ExportFile ref="exportRef" @download="downloadFun" />
  <!-- 表头设置 -->
  <TableWidthSet ref="tableTitleSet" @refresh="getList" />
  <!-- 作业者 -->
  <operator ref="operatorRef" @setOperator="setOperator" />
</template>

<script setup lang="ts" name="CourseElectricBox">
import { jumpPdfFile } from '@/utils/formCreate'
   import type { CrudSchema } from '@/hooks/web/useCrudSchemas'
   import download from '@/utils/download'
   import * as CourseElectricBoxApi from '@/api/produce/processManagement/courseElectricBox'
   import * as ComponentApi from '@/api/componentApi/index'
   import operator from '../components/operator.vue'
   const message = useMessage() // 消息弹窗
   const loading = ref(true) // 列表的加载中
   const total = ref(0) // 列表的总页数
   const list = ref([]) // 列表的数据
   const isEdit = ref(false) //是否指派
   const queryParams = reactive({
     pageNo: 1,
     pageSize: 50,
     workTaskNumber: null,
     productNumber: null,
     productName: null,
     partNumber: null,
     partName: null,
     drawingNumber: null,
     productionTeam: null
   })
   const queryFormRef = ref() // 搜索的表单
   const operatorRef = ref()
   const multipleTableRef = ref()
   const exportLoading = ref(false) // 导出的加载中

   const tableTitleList = ref<CrudSchema[]>([]) // 表头列表
   /** 查询列表 */
   const getList = async () => {
     loading.value = true
     try {
       const data = await CourseElectricBoxApi.getCourseElectricBoxPage(queryParams)
       list.value = data.list.map((item, index) => {
         item.parentIndex = index + 1 //父元素序号
         if (item.children.length) {
           item.children.map((child, childIndex) => {
             child.index = childIndex //子类编辑时的下标
             child.parent = index //父类下标
             return child
           })
         }
         return item
       })
       tableTitleList.value = data.labels
       total.value = data.total
     } finally {
       loading.value = false
     }
   }
   // 多选是否启用
   const isSelected = (row) => {
    if (isEdit.value) {
      if (!(row.parent === undefined)) {
        return false
      } else {
        return true
      }
    } else {
      return true
    }
   }

   const changeOperate = async () => {
     //保存
     if (isEdit.value) {
       if (!selectList.value.length) {
         message.error('请选择需要指派的数据')
         return
       }
       const data = selectList.value.map((item) => {
         const staffList = item.operator.split(',').map((val: string, i: number) => {
           return {
             staffName: val,
             jobNumber: item['operatorJobNumber'].split(',')[i]
           }
         })
         return {
           id: item['id'],
           deviceCode: item['deviceCode'],
           deviceName: item['deviceName'],
           staffList: staffList
         }
       })
       try {
         loading.value = true
         await CourseElectricBoxApi.assignCourseWelding({ assignList: data })
         message.success('指派成功')
         clearSelectData()
         getList()
       } finally {
         loading.value = false
         isEdit.value = false
       }
     } else {
       isEdit.value = true
       clearSelectData()
     }
   }

   /**选中 */
   const selectList = ref([])
   const handleSelectionChange = (data) => {
    if (data.length) {
      if (data[0].dictReportWay === 10) {
        selectList.value = data
      } else {
        selectList.value = data.filter((row) => row.children)
      }
    }
   }

   // 打开作业者弹窗
   const openOperator = (arr: [], parentIndex: number) => {
    operatorRef.value.open(arr, parentIndex)
    //  if (index !== undefined) {
    //    // 报工方式为进度时，设置细部工序作业者
    //    operatorRef.value.open(arr, index, true, parentIndex)
    //  } else {
    //    // 报工方式为计件时，设置作业者
    //    operatorRef.value.open(arr, parentIndex)
    //  }
   }

   // 设置作业者
   const setOperator = (parentIndex: number, index?: number) => {
    console.log(parentIndex)
    console.log(index)
     const operator = operatorRef.value.multipleSelection
     const operatorName = [] as string[]
     const operatorJobNumber = [] as string[]
     operator.map((item) => {
       operatorName.push(item['staffName'])
       operatorJobNumber.push(item['jobNumber'])
     })
     // 进度
    //  if (parentIndex !== undefined) {
    //    list.value[parentIndex].children[index].operator = operatorName.join(',')
    //    list.value[parentIndex].children[index].operatorJobNumber = operatorJobNumber.join(',')
    //  } else {
    //    list.value[index].operator = operatorName.join(',')
    //    list.value[index].operatorJobNumber = operatorJobNumber.join(',')
    //  }
    list.value[parentIndex - 1].operator = operatorName.join(',')
    list.value[parentIndex - 1].operatorJobNumber = operatorJobNumber.join(',')
  }

   //获取设备编码
   const deviceList = ref([])
   const deviceLoading = ref(false)
   const getSelectDeviceList = async (keyword: string) => {
     if (keyword) {
       deviceLoading.value = true
       try {
         deviceList.value = await ComponentApi.getDeviceList(keyword)
       } finally {
         deviceLoading.value = false
       }
     }
   }

   /**修改选择设备编码 */
   const changeDevice = (data: object) => {
     const name = deviceList.value.filter((item) => item['deviceCode'] == data['deviceCode'])[0][
       'deviceName'
     ]
     data['deviceName'] = name
   }

   /** 搜索按钮操作 */
   const handleQuery = () => {
     queryParams.pageNo = 1
     getList()
   }

   /** 重置按钮操作 */
   const resetQuery = () => {
     queryFormRef.value.resetFields()
     handleQuery()
   }
   /** 查看 */
   const { push } = useRouter() // 路由
   const openForm = (id: number) => {
     push({
       path: '/produce/produce/processManagement/courseElectricBox/CourseElectricBoxForm',
       query: {
         id
       }
     })
   }
   /** 导出按钮操作 */
   const exportRef = ref()
   const handleExport = () => {
     exportRef.value.open()
   }
   // 导出
   const downloadFun = async () => {
     const val = exportRef.value.params
     let params = {
       fileName: val.name,
       ids: ''
     }
     if (val.range === 'all') {
       params.ids = ''
     } else {
       params.ids = selectList.value.map((item) => item.id)
     }
     CourseElectricBoxApi.exportCourseElectricBox(params).then((res) => {
       download.excel(res, val.name)
       clearSelectData()
     })
   }

   //清空多选
   const clearSelectData = () => {
     selectList.value = []
     multipleTableRef.value!.clearSelection()
   }

   /**打开表格表头设置**/
   const tableTitleSet = ref()
   const openTableTitleSet = () => {
     let code = 'courseElectricBox'
     tableTitleSet.value.open(tableTitleList.value, code)
   }

   /** 初始化 **/
   const tableHeight = ref(0)
   //132：表格内除表格以外的高度，127 顶部固定高度 + copyright高度
   onMounted(async () => {
     const queryParamsHeight = queryFormRef.value.$el.clientHeight + 2
     tableHeight.value = document.body.clientHeight - 132 - queryParamsHeight - 127
     getList()
   })
</script>
